/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 28779
 * Date: 2023-11-05
 * Time: 17:36
 */
public class newHashBucket<K, V>{
     static class Node<K, V> {
        private K key;
        private V value;
        private Node<K, V> next;
        public Node(K key, V value) {
            this.key = key;
            this.value = value;
        }
    }
    public Node<K, V>[] array = (Node<K, V>[])new Node[10];
    public int usedSize;
    public static final float DEFAULT_LOAD_FACTOR = 0.75f;
    public newHashBucket() {
    }
    public void put(K key, V val) {
        Node<K, V> node = new Node<>(key, val);
        int hash = key.hashCode();
        int index = hash % array.length;

        Node<K,V> cur = array[index];

        while(cur != null) {
            if (cur.key.equals(key)) {
                cur.value = val;
                return;
            }
            cur = cur.next;
        }
        node.next = array[index];
        array[index] = node;

        usedSize ++;

        if(loadFactor() >= DEFAULT_LOAD_FACTOR) {
            resize();
        }
    }
    private float loadFactor() {
        return usedSize*1.0f / array.length;
    }
    public void resize () {
        Node[] tmpArray = new Node[array.length * 2];
        for (int i = 0; i < array.length; i++) {
            Node cur = array[i];
            while (cur != null) {
                Node curNext = cur.next;
                int hash = cur.key.hashCode();
                int index = hash % tmpArray.length;

                cur.next = tmpArray[index];
                tmpArray[index] = cur;

                cur = curNext;
            }
        }
        array = tmpArray;
    }
    public V getValue(K key) {
        int hash = key.hashCode();
        int index = hash % array.length;
        Node<K, V> cur = array[index];
        while (cur != null) {
            if (cur.key.equals(key)) {
                return cur.value;
            }
            cur = cur.next;
        }
        return null;
    }
}
